/**
 * 
 */
package it.robertobifulco.ias;

import java.util.ArrayList;

/**
 * @author Roberto Bifulco oltremago@gmail.com
 * 
 */
public class OperationList {

	private static OperationList operationList;

	private ArrayList<Operation> operations;
	private OperationRepository repository;

	private OperationList(OperationRepository repository) {

		this.operations = new ArrayList<Operation>(0);
		this.repository = repository;
	}

	public void addOperation(Operation operation) {
		this.operations.add(operation);

		this.toRepository();
	}

	public void addOperations(Operation[] operations) {

		for (int i = 0; i < operations.length; ++i) {
			this.operations.add(operations[i]);
		}

		this.toRepository();
	}

	public Operation getOperation(String id)
			throws NotDefinedOperationException {

		for (int i = 0; i < this.operations.size(); ++i) {
			if (((Operation) this.operations.get(i)).getID().equals(id)) {
				return (Operation) this.operations.get(i);
			}
		}

		throw new NotDefinedOperationException("Operation \"" + id
				+ "\" is not defined");
	}

	public void toRepository() {

		String[] identifiers = new String[this.operations.size()];
		String[] descriptions = new String[this.operations.size()];

		for (int i = 0; i < this.operations.size(); ++i) {
			identifiers[i] = ((Operation) this.operations.get(i)).getID();
			descriptions[i] = ((Operation) this.operations.get(i))
					.getDescription();
		}

		this.repository.updateOperationsList(identifiers, descriptions);
	}

	public void dispose() {
		this.operations = null;
		this.repository = null;

		OperationList.operationList = null;
	}

	public static OperationList createOperationList(
			OperationRepository repository) {

		if (operationList == null)
			operationList = new OperationList(repository);

		return operationList;
	}
}
